package com.itluma.openapi.apimapping.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itluma.openapi.apimapping.service.ApiMappingService;
import com.itluma.openapi.mapper.ApiMappingMapper;
import com.itluma.openapi.pojo.ApiMapping;
import com.itluma.openapi.pojo.ApiMappingExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class ApiMappingServiceImpl implements ApiMappingService {

    @Autowired
    private ApiMappingMapper apiMappingMapper;


    public PageInfo<ApiMapping> table(Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        ApiMappingExample example = new ApiMappingExample();
        List<ApiMapping> list = apiMappingMapper.selectByExample(example);
        return new PageInfo<ApiMapping>(list);
    }

    public PageInfo<ApiMapping> table(ApiMapping apiMapping, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);

        ApiMappingExample example = new ApiMappingExample();
        //设置各种条件
        ApiMappingExample.Criteria criteria = example.createCriteria();
        //名称
        if (apiMapping != null && !StringUtils.isEmpty(apiMapping.getGatewayapiname())) {
            criteria.andGatewayapinameLike("%" + apiMapping.getGatewayapiname() + "%");
        }

        //状态
        if (apiMapping != null && apiMapping.getState() != null) {
            criteria.andStateEqualTo(apiMapping.getState());
        }

        List<ApiMapping> list = apiMappingMapper.selectByExample(example);
        return new PageInfo<ApiMapping>(list);
    }


    public ApiMapping add(ApiMapping apiMapping) {//瞬时对象
        int rows = apiMappingMapper.insert(apiMapping);//持久化对象
        if (rows > 0) {
            return apiMapping;
        }
        return null;
    }


    @Transactional
    public ApiMapping edit(ApiMapping apiMapping) {
        int rows = apiMappingMapper.updateByPrimaryKeySelective(apiMapping);

        //其他业务流程
//        int i = 1 / 0;

        if (rows > 0) {
            return apiMapping;
        }
        return null;
    }

    @Override
    @Transactional
    public Boolean delete(Integer[] id) {
        int rows=0;
        for (Integer integer : id) {
            apiMappingMapper.deleteByPrimaryKey(integer);
            rows++;
        }
        if (rows > 0) {
            return true;
        }
        return false;
    }
}
